package api

import (
	"api/config"
	"api/internal/api/request"
	"api/internal/api/response"
	"api/internal/handler"
	"api/pkg"
	"flag"
	"github.com/gin-gonic/gin"
	"strconv"
	pb "user_srv/proto"
)

var (
	address    = config.SrvConfigs.UserSrv.Host + ":" + strconv.Itoa(config.SrvConfigs.UserSrv.Port)
	userServer = flag.String(config.SrvConfigs.UserSrv.Name, address, "The server address")
	userSrv    = handler.NewClient().UserServer(userServer)
)

func Register(c *gin.Context) {
	var json *request.Register
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Register(c, &pb.RegisterRequest{
		Tel:      json.Tel,
		Password: json.Password,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "注册成功", register.Id)
}

func Login(c *gin.Context) {
	var json *request.Login
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	register, err := userSrv.Login(c, &pb.LoginRequest{
		Tel:      json.Tel,
		Password: json.Password,
		SendCode: json.SendMessage,
	})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	tokenHandler, _ := pkg.TokenHandler(strconv.FormatInt(register.Id, 10))
	response.Response(c, 200, "登录成功", tokenHandler)
}

func Send(c *gin.Context) {
	var json *request.Send
	if err := c.ShouldBindJSON(&json); err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	message, err := userSrv.SendMessage(c, &pb.SendMessageRequest{Tel: json.Tel})
	if err != nil {
		response.Response(c, 400, err.Error(), nil)
		return
	}
	response.Response(c, 200, "短信发送成功", message)
}
